package cn.com.libertymutual.core.database.druid.config;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import cn.com.libertymutual.core.database.druid.DataSourceContextHolder;
import cn.com.libertymutual.core.database.druid.DataSourceType;

public class SalePlatAbstractRoutingDataSource extends
		AbstractRoutingDataSource {
	private final int dataSourceNumber;
	private AtomicInteger count = new AtomicInteger(0);

	public SalePlatAbstractRoutingDataSource(int dataSourceNumber) {
		this.dataSourceNumber = dataSourceNumber;
	}

	@Override
	protected Object determineCurrentLookupKey() {
		String typeKey = DataSourceContextHolder.getJdbcType();
		if (DataSourceType.write.getType().equals(typeKey))
			return DataSourceType.write.getType();
		// 读 简单负载均衡
		int number = count.getAndAdd(1);
		int lookupKey = number % dataSourceNumber;
		return new Integer(lookupKey);
	}

}
